#!/bin/bash -eu
#
# Copyright 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

readonly db_username="liferay"
readonly db_password="${liferay_db_password:-$(get_attribute_value "liferay-db-password")}"
readonly db_name="liferay"

# Create liferay user and database
mysql -u root -e "CREATE USER '${db_username}'@'localhost' IDENTIFIED BY '${db_password}';"
mysql -u root -e "GRANT ALL PRIVILEGES ON ${db_name}.* TO '${db_username}'@'localhost' IDENTIFIED BY '${db_password}'";
mysql -u root -e "FLUSH PRIVILEGES"

# Add DB credentials to config file
cd /opt/liferay/tomcat*/webapps/ROOT/WEB-INF/classes/
cat << EOF > portal-ext.properties
jdbc.default.url=jdbc\:mysql\://localhost/${db_name}?useUnicode\=true&characterEncoding\=UTF-8&useFastDateParsing\=false
jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.username=${db_username}
jdbc.default.password=${db_password}
EOF
chown liferay:liferay portal-ext.properties
